<template>
  <div class="scroll-bar" :style="{width:swidth + '%'}"></div>
</template>

<script>
export default {
  props: {
    callback: {
      type: Function,
      default() {
        return function () { }
      }
    }
  },
  data() {
    return {
      clientH: 0,
      totalH: 0,
      swidth: 0
    }
  },
  mounted() {
    let sTop = 0,
      scrollH = 0,
      _self = this

    this.totalH = document.body.scrollHeight || document.documentElement.scrollHeight

    window.addEventListener(
      'scroll',
      function () {
        let clientH = document.body.offsetHeight || document.documentElement.offsetHeight
        sTop = clientH - _self.totalH
        // 滚动条卷去高度
        scrollH = document.body.scrollTop || document.documentElement.scrollTop

        // 百分比
        _self.swidth = Math.ceil(scrollH / sTop * 100);
        _self.callback(_self.swidth, scrollH);
      },
      false
    )
  }
}
</script>

<style lang="scss" scoped>
.scroll-bar {
  position: fixed;
  top: 0;
  left: 0;
  height: 2px;
  background: var(--theme);
  transition: width 0.2s;
  z-index: 100;
}
</style>